<template>
	<view class="sa_content">
		<!-- 返回，默认返回首页 -->
		<view class="sa_return">
			<image :src="HTTP_IMG_UTL+'fanhui.png'" style="width: 28rpx;height: 40rpx;" mode=""
				@click="handelReturn" />
			<view></view>
		</view>
		<!-- 认证您的身份 -->
		<view class="sa_imgs">
			<image :src="HTTP_IMG_UTL+'authentication_282@2x.png'" mode=""
				style="width:376rpx;height: 55rpx;" v-if="lang==='zh'" />
			<view v-if="lang==='ru'" style="font-size: 36rpx;font-weight: bold;">Подтверждение информации вашей компании
			</view>
			<view style="color: #404040;margin-top: 18rpx;" v-if="lang==='zh'">将获得智能助手，精准推送及专属图标</view>
			<view style="color: #404040;margin-top: 18rpx;" v-if="lang==='ru'">Получить виртуального помощника,
				push-уведомления и эксклюзивный значок</view>
		</view>
		<!-- 经营范围文字 -->
		<view class="sa_nationality_title">
			<view>{{$t('经营范围')}}</view>
		</view>
		<view class="sa_sales">
			<u-input :clearable="clearable" maxlength="200" count :placeholder="$t('请输入经营范围')" v-model="value"
				:type="type" :border="border" :height="heights" :auto-height="autoHeight" />
		</view>
		<!-- 主营产品类目文字 -->
		<view class="sa_License_title">
			<view>{{$t('主营产品类目')}}</view>
		</view>
		<!-- 一级类目，二级类目  新增图标 -->
		<view class="sa_class">
			<view class="sa_class_left">
				<view style="width: 50%;display: flex;justify-content: flex-start;">
					<view>{{$t('一级类目')}}</view>
				</view>
				<view style="width: 50%;display: flex;justify-content: flex-start;">
					<view style="margin-left: 50rpx;">{{$t('二级类目')}}</view>
				</view>
			</view>
			<!-- 新增图标 -->
			<view>
				<image v-if="addSow" style="width: 30rpx;height: 30rpx;"
					:src="HTTP_IMG_UTL+'add_239@2x.png'" @click="handelAdd" />

			</view>
		</view>

		<!-- 类目列表 -->
		<view class="sa_foo">
			<view v-for="(item,index) in classList" :key="index" class="sa_items">
				<!-- 一级类目 -->
				<view class="sa_one" @click="handelOne(index)">
					<view v-if="item.oneTitle" class="sa_oneTitle">{{item.oneTitle}}</view>
					<view style="color: color: #A4A4A4;" v-else>{{$t('请选择类目')}}</view>
					<image :src="HTTP_IMG_UTL+'right_218@2x.png'" mode=""
						style="width: 20rpx;height: 12rpx;" />
				</view>
				<!-- 分割线 -->
				<view class="sa_line"></view>
				<!-- 二级类目 -->
				<view class="sa_tow" @click="handeleTow(index)">
					<view v-if="item.towTitle.length!=0" class="sa_towTitle">
						<span v-if="lang==='zh'"> {{ item.towTitle.map(item => item.name).join(', ') }}</span>
						<span v-if="lang==='ru'"> {{ item.towTitle.map(item => item.name_ru).join(', ') }}</span>
					</view>
					<view class="ejlist" s v-else>{{$t('请选择（可多选）')}}</view>
					<view class="sa_del">
						<!-- 下拉图标 -->
						<image :src="HTTP_IMG_UTL+'right_218@2x.png'" mode=""
							style="width: 20rpx;height: 12rpx;margin-right: 5rpx;" />
						<!-- 删除图标 -->
						<image v-if="classList.length > 1" @click.stop="handelDel(index,item.oneId)"
							:src="HTTP_IMG_UTL+'del_242@2x.png'" mode=""
							style="width: 30rpx;height: 30rpx;margin-left: 25rpx;" />
					</view>
				</view>
			</view>
		</view>

		<!-- 营业执照文字 -->
		<view class="sa_License_title">
			<view v-if="lang==='zh'">{{$t('营业执照')}} ({{$t('选填')}})</view>
			<view v-if="lang==='ru'">{{$t('认证视频')}} ({{$t('选填')}})</view>
		</view>
		<view class="sa_detail" v-if="lang==='ru'">
			Запишите видеоподтверждение, в котором вы произносите следующее: “Я - российский поставщик. Хочу продавать
			товары из России на платформе GLUZ, в связи с этим подаю заявку на подтверждение.”
		</view>
		<view class="sa_images">
			<!-- 上传图片 -->
			<u-upload v-if="lang==='zh'" style="margin-top: 30rpx;padding: 0rpx;margin-left: -10rpx;" :action="action"
				:file-list="list" :max-size="imageMaxSize" :max-count="max_count" :width="width" :height="height"
				:auto-upload="autoUpload" :show-upload-list="showUploadList" :del-bg-color="delBgColor"
				:del-color="delColor" :upload-text="uploadText" :limit-type="limitType" @on-success="onSuccess"
				@on-remove="onRemove" :show-progress="showProgress" />
		</view>
		<view v-if="lang==='ru'" style="margin-top: 68rpx;">
			<formVideos :item="formItem" :postvideo="videoData" :postid="postId" @change="selVideos" />
		</view>
		<view class="sa_but">
			<view class="but_left">
				<u-button @click="handelReturn">{{$t('上一步')}}</u-button>
			</view>
			<view class="but_right">
				<u-button class="custom-style" :loading="isLoading" :disabled="isDisabled"
					@click="submit">{{$t('认证')}}</u-button>
			</view>
		</view>

		<!-- 下面是弹窗 -->

		<!-- 一级类目底部弹窗 -->
		<u-picker v-model="show" mode="selector" :range="arrList" :range-key="lang=='zh'?'name':'name_ru'"
			:confirm-text="$t('确定')" :cancel-text="$t('取消')" @confirm="handelConfirm" />
		<!-- :default-selector="[indexID]" -->
		<u-popup v-model="isShow" mode="bottom" border-radius="14">
			<view class="sa_popuo">
				<view class="sa_confim">
					<view style="color: #999999;" @click="handeleCancel(0)">{{$t('取消')}}</view>
					<view style="color: #333333;" @click="handeleCancel(1)">{{$t('确定')}}</view>
				</view>
				<view class="sa_pop">
					<scroll-view class="uni-swiper-tab" scroll-y>
						<view style="width: 100%;">
							<u-checkbox-group @change="checkboxGroupChange" style="width: 100%;">
								<view class="checkbox-group">
									<view v-for="(item,index) in arrListTow" :key="index" class="checkbox_item">
										<text class="checkbox-text">{{lang==='zh'?item.name:item.name_ru}}</text>
										<u-checkbox :name="item.id" v-model="item.checked" />
									</view>
								</view>
							</u-checkbox-group>
						</view>
					</scroll-view>
				</view>
			</view>
		</u-popup>
		<view class="backColor"></view>
	</view>
</template>

<script>
	import {
		IMAGE_URL,
		HTTP_IMG_UTL
	} from "@/config/app";
	import formVideos from "./components/formVideos.vue";
	import {
		HTTP_REQUEST_URL,
		IMAGE_MAX_SIZE,
		IMAGE_MAX_COUNT
	} from '@/config/app';
	export default {
		components: {
			formVideos
		},
		data() {
			return {
				HTTP_IMG_UTL,
				isDisabled: false,
				isLoading: false,
				formItem: {
					required: false,
					label: '',
					key: 'video',
					value: []
				},
				videoData: '', // 假设这是视频URL或相关数据
				postId: 0, // 假设这是商品或帖子的ID
				// ------------------------------------------------
				isShow: false, //控制二级类目显示和隐藏
				show: false, //控制一级类目显示和隐藏
				arrList: [], //一级类目遍历的数据
				arrListContrast: [], //一级类目对比的数据
				arrListTow: [], //二集类目
				SelectCategory: [], //选中二级分类
				classList: [{
					one: '请选择类目',
					tow: '请选择（可多选）',
					oneTitle: '',
					towTitle: [],
					oneId: '',
					towId: ''
				}, ],
				showProgress: false, //图片上传配置
				width: '600', //图片上传配置
				height: '212', //图片上传配置
				autoUpload: true, //图片上传配置
				showUploadList: true, //图片上传配置
				delBgColor: '#fa3534', //图片上传配置
				delColor: '#ffffff', //图片上传配置
				max_count: 1, //图片上传的最大数量
				action: HTTP_REQUEST_URL + '/common/upload', //服务器上传地址
				imageMaxSize: IMAGE_MAX_SIZE, //图片上传配置
				imageMaxCount: IMAGE_MAX_COUNT, //图片上传配置
				uploadText: this.$t('请上传营业执照副本照片'), //图片上传配置
				limitType: ['png', 'jpg', 'jpeg', 'webp', 'gif', 'image'], //图片上传配置
				clearable: false,
				value: '', //承接业务
				type: 'textarea',
				border: true,
				heights: 218,
				autoHeight: true,
				lang: 'zh',
				nowLang: 'zh', //获取协议接口使用的当前语言
				list: [], //默认显示的图片列表，数组元素为对象，必须提供url属性
				formDatas: [], //图片列表
				data: {}, //传过来的数据
				classIndex: 0, // 一级分类选择的下标
				addSow: true,
				userid: '',
				videoUrl: ''
			}
		},
		onLoad(option) {
			this.data = JSON.parse(option.data)
		},
		onShow() {
			this.nowLang = this.$i18n.locale
			// 获取当权语言
			this.getLang()
			// 获取一级类目
			this.getActionSheet()
			this.arrListTow = []
		},
		methods: {
			// 获取到视频
			selVideos(key, value) {
				this.videoUrl = value[0].url
			},
			// 认证
			submit() {
				let isShow = false
				this.classList.forEach(item => {
					if (!item.oneTitle) {
						uni.showToast({
							title: this.$t('一级类目不能为空'),
							icon: 'none',
							duration: 1000
						})
						isShow = true
						return
					}
				})
				if (isShow) {
					return
				}
				if (this.value === '') {
					uni.showToast({
						title: this.$t('请输入经营范围'),
						icon: 'none',
						duration: 1000
					})
				} else if (this.lang === 'zh') {
					this.getApi()
					return;
					if (this.formDatas.length === 0) {
						uni.showToast({
							title: this.lang === 'zh' ? this.$t('请上传营业执照副本照片') : this.$t('请上传视频'),
							icon: 'none',
							duration: 1000
						})
					} else {
						this.getApi()
					}
				} else if (this.lang === 'ru') {
					this.getApi()
					return;
					if (this.videoUrl === '') {
						uni.showToast({
							title: this.lang === 'zh' ? this.$t('请上传营业执照副本照片') : this.$t('请上传视频'),
							icon: 'none',
							duration: 1000
						})
					} else {
						this.getApi()
					}
				}

			},
			// 调用接口认证
			getApi() {
				this.data.main_product = this.value //经营范围
				if (this.formDatas.length !== 0) {
					this.data.license_image = this.formDatas.toString()
				}
				this.data.agent_code = "" //暂时无所谓
				this.data.user_id = this.userid //用户id
				this.data.video = this.videoUrl ? this.videoUrl : '' //视频

				let notifications = this.classList.map(item => ({
					id: item.oneId,
					name: item.oneTitle,
					chind: item.towTitle.map(child => ({
						id: child.id,
						name: child.name
					}))
				}));
				this.data.notifications = JSON.stringify(notifications)
				this.isDisabled = true
				this.isLoading = true
				this.$u.api.release.newProfile(this.data).then(res => {
					this.isDisabled = false
					this.isLoading = false
					// 给用户一个提示
					uni.showToast({
						title: this.$t('认证成功'),
						icon: 'none',
						duration: 1000
					})
					// 一秒后跳转到认证页面
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/tabbar/index'
						})
					}, 1000)
				}).catch(err => {
					this.isDisabled = false
					this.isLoading = false
					uni.showToast({
						title: this.$t('认证失败'),
						icon: 'none',
						duration: 1000
					})
				})
			},
			// 一级分类下拉
			handelConfirm(e) {
				let index = e[0] //下拉选中商品的下标
				//根据当前选中的类目下标获取值
				if (this.lang === 'zh') {
					this.classList[this.classIndex].oneTitle = this.arrList[index].name
				} else {
					this.classList[this.classIndex].oneTitle = this.arrList[index].name_ru
				}
				//根据当前选中的类目下标获取值
				this.classList[this.classIndex].oneId = this.arrList[index].id
				// 获取二级类目
				this.getActionSheetTow(this.arrList[index].id)
				// 一级类目切换则清空二级类目之前的选项
				this.classList.forEach((item, index) => {
					if (item.oneId === this.arrList[e[0]].id) {
						this.classList[index].towTitle = []
					}
				})
				// 一分类处理
				this.setData()
			},
			// 一级分类数据处理
			setData() {
				// arrList            一级分类
				// arrListContrast    一级分类对比
				let array2 = this.classList.map(item => ({
					id: item.oneId,
					name: item.oneTitle
				}))
				//  创建一个包含 array2 中所有 id 的集合
				const idsToExclude = new Set(array2.map(item => item.id));
				// 生成新的数组，不包含 array2 中的 id
				this.arrList = this.arrListContrast.filter(item => !idsToExclude.has(item.id));


			},
			// 选中任一checkbox时，由checkbox-group触发
			checkboxGroupChange(e) {
				this.SelectCategory = e
			},
			// 二级分类操作的确定和取消
			handeleCancel(e) {
				if (e === 0) {
					this.isShow = false
				} else if (e === 1) {
					const titles = this.arrListTow
						.filter(item => this.SelectCategory.includes(item.id))
						.map(item => ({
							...item,
							checked: true
						}));
					this.isShow = false
					this.classList[this.classIndex].towTitle = titles
				}
			},

			// 二级类目点击选择
			handeleTow(index) {
				this.classIndex = index
				this.getActionSheetTow(this.classList[index].oneId)
				this.isShow = !this.isShow
			},
			// 一级类目点击选择
			handelOne(index) {
				this.classIndex = index
				this.show = !this.show
			},
			// 新增类目
			handelAdd() {
				this.classList.push({
					one: '请选择类目',
					tow: '请选择（可多选）',
					oneTitle: '',
					towTitle: [],
					oneId: '',
					towId: ''
				})
				if (this.classList.length >= this.arrList.length) {
					this.addSow = false
				} else {
					this.addSow = true
				}

			},
			// 删除类目
			handelDel(index, id) {
				uni.showModal({
					title: this.$t('温馨提示'),
					content: this.$t('确认删除此类目'),
					cancelText: this.$t('否'),
					confirmText: this.$t('是'),
					success: res => {
						if (res.confirm) {
							this.classList.splice(index, 1)
							if (this.classList.length < this.arrList.length) {
								this.addSow = true
							}
							this.setData()
						}
					}
				})

			},
			// 获取一级分类
			getActionSheet() {
				let data = {
					type: 'release_goods',
					lang: this.lang,
					pid: 0
				}
				this.$u.api.basic.getActionSheetList(data).then(res => {
					// 显示的数组
					this.arrList = res
					this.arrListContrast = res //一级分类对比
				})
			},
			// 获取二级类目
			getActionSheetTow(pid) {
				let data = {
					type: 'release_goods',
					lang: this.lang,
					pid: pid
				}
				this.$u.api.basic.getActionSheetList(data).then(res => {
					if (this.classList[this.classIndex].towTitle.length != 0) {
						const arr = res
						const ids = this.classList[this.classIndex].towTitle
						const idsMap = new Map(ids.map(item => [item.id, item.checked]));
						const updatedArr = arr.map(item => ({
							...item,
							checked: idsMap.has(item.id) ? idsMap.get(item.id) : false
						}));
						this.arrListTow = updatedArr
					} else {
						if(pid){
							this.arrListTow = res
						}
						
					}
				})
			},
			// 返回上一页

			// 获取当权语言
			getLang() {
				// 获取缓存lang当前语言值
				uni.getStorage({
					key: 'lang',
					success: res => {
						if (res.data == 'zh') { //zh为中国，赋值0
							this.lang = 'zh'
						} else { //其他为俄罗斯，赋值1
							this.lang = 'ru'
						}
					}
				});
				uni.getStorage({
					key: 'user_id',
					success: res => {
						this.userid = res.data
					}
				});
			},
			// 返回上一页
			handelReturn() {
				uni.navigateBack()
			},
			// 上传成功
			onSuccess(data, index, lists, name) {
				// 将照片插入数组
				this.formDatas.push(lists[0].response.data.url)
			},
			// 删除图片
			onRemove(index, lists, name) {
				//删除照片
				this.formDatas.splice(index, 1)
			},
			removeTrailingDot(str) {
				// return str.replace(/\.$,/, ''); // 使用正则表达式替换末尾的点
				return str.replace(/,$/, '')
			}
		}
	}
</script>

<style lang="scss" scoped>
	.ejlist {
		width: 200rpx;
		word-break: break-all;
		overflow: hidden;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;

	}

	.backColor {
		width: 100%;
		height: 1202rpx;
		background: linear-gradient(180deg, #E1F8C7 -3%, rgba(255, 255, 255, 0.2) 56%);
		position: absolute;
		top: 0;
		z-index: -1;
	}

	.sa_detail {
		width: calc(100% - 60rpx);
		margin-top: 32rpx;
		font-size: 24rpx;
		color: #A4A4A4;
	}

	.checkbox-text {
		font-size: 28rpx;
	}

	.checkbox_item {
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.checkbox-group {
		width: 100%;
		display: flex;
		flex-direction: column;
		/* 纵向排列 */
	}

	.sa_confim {
		width: calc(100% - 100rpx);
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
	}

	.uni-swiper-tab {
		height: 100%;
	}

	.sa_pop {
		width: 90%;
		height: 600rpx;
	}

	.sa_popuo {
		width: 100%;
		height: 746rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.sa_towTitle {
		width: 300rpx;
		height: 40rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.sa_oneTitle {
		width: 80%;
		height: 40rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.sa_del {
		display: flex;
		align-items: center;
	}

	.sa_tow {
		// flex: 1;
		width: 50%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.sa_one {
		width: 40%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-right: 5%;
	}

	.sa_foo {
		width: calc(100% - 60rpx);

	}

	.sa_items {
		width: 100%;
		height: 80rpx;
		display: flex;
		align-items: center;
	}

	.sa_line {
		width: 4rpx;
		height: 24rpx;
		background-color: #000000;
		margin-right: 5%;
	}

	.sa_class_left {
		width: 80%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 24rpx;
		font-weight: 600;
	}

	.sa_class {
		width: calc(100% - 60rpx);
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-top: 40rpx;
	}

	.custom-style {
		background-color: #000000;
		color: #ffffff;
	}

	.but_left {
		width: 20%;
	}

	.but_right {
		width: 75%;
	}

	.sa_but {
		margin: 74rpx 0 74rpx 0;
		width: calc(100% - 60rpx);
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.sa_images {
		width: calc(100% - 60rpx);
		display: flex;
		justify-content: flex-start;
	}

	.sa_License_title {
		width: calc(100% - 60rpx);
		font-size: 28rpx;
		display: flex;
		justify-content: flex-start;
		font-weight: 600;
		margin-top: 30rpx;
	}

	.sa_sales {
		width: calc(100% - 60rpx);
		margin-top: 24rpx;
	}

	.sa_nationality_title {
		width: calc(100% - 60rpx);
		font-size: 28rpx;
		display: flex;
		justify-content: flex-start;
		font-weight: 600;
		margin-top: 60rpx;
	}

	.sa_imgs {
		margin-top: 18rpx;
		width: calc(100% - 60rpx);
		display: flex;
		flex-direction: column;
	}

	.sa_return {
		margin-top: 110rpx;
		width: calc(100% - 60rpx);
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.sa_content {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
</style>